package com.c.ctgproject.ui.production.doing

import android.app.Activity
import android.content.Intent
import android.os.Environment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.c.ctgproject.R
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.customview.GlideImageLoader
import com.c.ctgproject.customview.ImagePickerLoader
import com.c.ctgproject.utils.CustomToast
import com.c.ctgproject.utils.MyLog
import com.c.ctgproject.utils.showToast
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.imagepicker.data.ImagePickType
import com.lwkandroid.widget.ninegridview.NineGirdImageContainer
import com.lwkandroid.widget.ninegridview.NineGridBean
import com.lwkandroid.widget.ninegridview.NineGridView
import com.nanchen.compresshelper.CompressHelper
import kotlinx.android.synthetic.main.activity_doing_production.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONObject
import java.io.File

/**
 *作者:LiBW
 *创建日期: 2020/9/4
 *描述: 生产中
 */
class DoingProductionActivity : BaseActivity() {
    private val files1: ArrayList<File> = ArrayList()
    private val requestCodePicker = 1001
    private var mCarId = ""
    private val mViewModel: DoingProductionViewModel by lazy { ViewModelProvider(this)[DoingProductionViewModel::class.java] }

    override fun getLayout() = R.layout.activity_doing_production

    override fun event() {
        val data = intent.getStringExtra("Message")
        data?.let {
            val json = JSONObject(it)
            val carCode = json.getString("carCode")
            val weightBeforeDis = json.getString("weightBeforeDis")
            val proInTime = json.getString("proInTime")
            val carId = json.getString("carId")
            mCLBH.text = carCode
            mSCQZL.text = weightBeforeDis
            mJRSCQSJ.text = proInTime
            mCarId = carId
        }


        //拆解完成上传图片回调
        mViewModel.upFile.observe(this, Observer {
            loading.dismiss()
            if (it == null) return@Observer
            MyLog.d("拆解完成上传图片回调${it.data}")
            MyLog.d("拆解完成上传图片回调${it.msg}")
            CustomToast.showToast(this, it.msg.toString())
            if (it.status == 0) {
                finish()
            }
        })

        mViewModel.error.observe(this, Observer {
            loading.dismiss()
            CustomToast.showToast(this, it)
        })


        changeTransparentStatusBar()
        changeStatusIconColor(true)
        mViewModel.error.observe(this, Observer {
            CustomToast.showToast(this, it)
        })

        //设置图片加载器，这个是必须的，不然图片无法显示
        mScanQrBTN.setImageLoader(GlideImageLoader())
        //设置显示列数，默认3列
        mScanQrBTN.setColumnCount(1)
        //设置是否为编辑模式，默认为false
        mScanQrBTN.setIsEditMode(true)
        //设置单张图片显示时的尺寸，默认100dp
        mScanQrBTN.setSingleImageSize(150)
        //设置单张图片显示时的宽高比，默认1.0f
        mScanQrBTN.setSingleImageRatio(0.8f)
        //设置最大显示数量，默认9张
        mScanQrBTN.setMaxNum(1)
        //设置图片显示间隔大小，默认3dp
        mScanQrBTN.setSpcaeSize(4)
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        mScanQrBTN.setRatioOfDeleteIcon(0.15f)
        //设置“+”号的图片
        mScanQrBTN.setIcAddMoreResId(R.mipmap.takephoto)
        //设置各类点击监听
        mScanQrBTN.setOnItemClickListener(object : NineGridView.onItemClickListener {
            override fun onNineGirdItemDeleted(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {
                if (files1.isEmpty()) {
                    files1.removeAt(position)
                }
            }

            override fun onNineGirdItemClick(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {

            }

            override fun onNineGirdAddMoreClick(cha: Int) {
                //编辑模式下，图片展示数量尚未达到最大数量时，会显示一个“+”号，点击后回调这里
                val imageLoader = ImagePicker()
                    .cachePath(Environment.getExternalStorageDirectory().absolutePath)
                    .pickType(ImagePickType.MULTI)
                    .displayer(ImagePickerLoader())
                    .maxNum(cha)
                    .start(this@DoingProductionActivity, requestCodePicker)
            }

        })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == requestCodePicker && resultCode == Activity.RESULT_OK && data != null) {
            val list: List<ImageBean> = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
            val resultList: MutableList<NineGridBean> = java.util.ArrayList()
            for (imageBean in list) {
                val nineGirdData = NineGridBean(imageBean.imagePath)
                val file = File(imageBean.imagePath)
                val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
                files1.add(newFile)
                resultList.add(nineGirdData)
            }
            mScanQrBTN.addDataList(resultList)
        }
    }


    override fun click() {
        //拆解完成
        mConfirmRL.setOnClickListener {
            if (files1.isEmpty()) {
                showToast("请拍照")
                return@setOnClickListener
            }
            loading.show()
            val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files1[0])
            val part = MultipartBody.Part.createFormData("picture", files1[0].name, requestFile)
            MyLog.d("上传的carID:$mCarId")
            val fb = RequestBody.create(MediaType.parse("text/plain"), mCarId)

            mViewModel.upFile(fb, part)
        }
    }

}